package cn.dark.auth.core;

import cn.dark.auth.core.AuthSession.TokenInfo;
import cn.dark.auth.core.exception.AuthBaseException;
import cn.dark.auth.core.repository.LoginRepository;
import cn.dark.auth.core.tokengenerate.TokenGenerator;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 登录核心逻辑
 *
 * @author dark
 * @date 2023-10-22
 */
@Slf4j
public class LoginCore {

    public static String login(Long loginId) {
        return login(loginId, CommonConstant.DEFAULT_DEVICE);
    }

    /**
     * 登录
     *
     * @param loginId 账号id
     * @param deviceType 设备类型，默认为default
     * @return
     */
    public static String login(Long loginId, String deviceType) {
        checkParam(loginId, deviceType);

        if (StringUtils.isBlank(deviceType)) {
            deviceType = CommonConstant.DEFAULT_DEVICE;
        }

        // 是否允许不同设备同时登录
        LoginRepository loginRepository = SpringUtil.getBean(LoginRepository.class);
        String sessionKey = KeyGenerateUtil.getSessionKeyByLoginId(loginId);
        AuthSession session = loginRepository.getSession(sessionKey);
        if (Objects.nonNull(session)) {
            if (SysConfig.isConcurrent()) {
                String oldToken = session.removeTokenInfoByDevice(deviceType);
                log.info("允许不同客户端同时登录，当前账号id:{}, 设备类型:{}, oldToken: {}", loginId, deviceType, oldToken);

                if (StringUtils.isNotBlank(oldToken)) {
                    loginRepository.removeObject(KeyGenerateUtil.getKeyByToken(oldToken));
                }
            } else {
                List<String> allOldToken = session.getAllToken();
                if (CollUtil.isNotEmpty(allOldToken)) {
                    log.info("不允许同时登录，移除所有已经存在的token: {}", allOldToken);
                    allOldToken.forEach(item -> loginRepository.removeObject(KeyGenerateUtil.getKeyByToken(item)));
                }
                loginRepository.removeObject(sessionKey);
            }
        }

        // 获取token
        TokenGenerator tokenGenerator = SpringUtil.getBean(TokenGenerator.class);
        String token = tokenGenerator.generateToken(loginId, deviceType);

        // 生成及保存session
        saveSession(loginId, deviceType, loginRepository, sessionKey, token);

        // 保存token与账号id的映射关系
        loginRepository.saveObject(KeyGenerateUtil.getKeyByToken(token), loginId, SysConfig.getTimeOut());

        log.info("登录成功");

        return token;
    }

    private static void checkParam(Long loginId, String deviceType) {
        if (Objects.isNull(loginId)) {
            throw new AuthBaseException("账号id不能为空");
        }

        if (SysConfig.getAbnormalaccounts().contains(loginId)) {
            throw new AuthBaseException("账号已被拉黑，无法登录");
        }
    }

    private static void saveSession(Long loginId, String deviceType, LoginRepository loginRepository, String sessionKey,
                                    String token) {
        AuthSession session = loginRepository.getSession(sessionKey);
        if (Objects.isNull(session)) {
            session = new AuthSession(loginId);
        }

        TokenInfo tokenInfo = new TokenInfo(token, deviceType, new Date(), new Date());
        session.addTokenInfo(tokenInfo);

        loginRepository.saveSession(sessionKey, session, SysConfig.getTimeOut());
    }

    /**
     * 判断token是否是有效token
     *
     * @param token
     * @return
     */
    public static boolean isLogin(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        }

        LoginRepository loginRepository = SpringUtil.getBean(LoginRepository.class);
        Object loginId = loginRepository.getObject(KeyGenerateUtil.getKeyByToken(token));
        if (Objects.isNull(loginId)) {
            return false;
        }

        if (SysConfig.getAbnormalaccounts().contains(loginId)) {
            log.info("账号异常，无法使用，loginId: {}", loginId);
            return false;
        }

        return true;
    }

    public static Long getLoginIdByToken(String token) {
        LoginRepository loginRepository = SpringUtil.getBean(LoginRepository.class);
        return (Long) loginRepository.getObject(KeyGenerateUtil.getKeyByToken(token));
    }

    public static String getTokenByUserId(Long userId, String device) {
        if (StringUtils.isBlank(device)) {
            device = CommonConstant.DEFAULT_DEVICE;
        }

        LoginRepository loginRepository = SpringUtil.getBean(LoginRepository.class);
        AuthSession session = loginRepository.getSession(KeyGenerateUtil.getSessionKeyByLoginId(userId));
        if (Objects.isNull(session)) {
            return null;
        }

        String finalDevice = device;
        TokenInfo tokenInfo = session.getTokenInfos().stream()
                .filter(item -> finalDevice.equals(item.getDevice())).findFirst().orElse(null);
        if (Objects.isNull(tokenInfo)) {
            return null;
        }
        return tokenInfo.getToken();
    }
}
